package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Permissions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 检查用户是否登录
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html
        //2、获取本次请求的方式
        String method = request.getMethod();
        log.info("拦截到请求：{}",requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login",//移动端登录
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3、如果不需要处理，则直接放行
        if (check) {
//            log.info("不需要处理的请求：{}",requestURI);
            filterChain.doFilter(request,response);
            //执行完方法后,删除这次 threadLocal 内存储的id的值;否则可能会存在内存泄露问题
            BaseContext.remove();
            return;
        }

        //4-1、判断登录状态，如果已登录，则直接放行
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if (employee != null) {
            Long empId = (Long) session.getAttribute("employee");
//            log.info("已登录，用户id为：{}",empId);
            //设置这次线程的EmpId
            BaseContext.setCurrentId(empId);
            if (empId == 1) {//该用户是管理员
                //放行方法
                filterChain.doFilter(request, response);
            } else {
                //查看该员工是否有执行该方法的权限
                List<Permissions> permissions = (List<Permissions>) session.getAttribute("permissions");
                //本次请求所需要的权限
                Boolean power = false;
                for (Permissions permission : permissions) {
                    if (permission.getMethodType().equals(method) && permission.getUrl().equals(requestURI)) {
                        //存在
                        power = true;
                    }
                }
                if (power) {
                    //存在，放行方法
                    filterChain.doFilter(request, response);
                } else {
                    //创建Jackson的核心对象
                    ObjectMapper mapper = new ObjectMapper();
                    //写入提示信息
                    R<String> msg = R.error("NO_PERMISSION");
                    //转为JSON字符串
                    String json = mapper.writeValueAsString(msg);
                    //通过response返回给前端
                    response.getWriter().write(json);
                }
            }
            //执行完方法后,删除这次 threadLocal 内存储的id的值;否则可能会存在内存泄露问题
            BaseContext.remove();
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        Object user = session.getAttribute("user");
        if (user != null) {
            Long userId = (Long) session.getAttribute("user");
//            log.info("已登录，用户id为：{}",userId);
            //设置这次线程的EmpId
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            //执行完方法后,删除这次 threadLocal 内存储的id的值;否则可能会存在内存泄露问题
            BaseContext.remove();
            return;
        }

        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        log.info("用户未登录：{}",requestURI);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //执行完方法后,删除这次 threadLocal 内存储的id的值;否则可能会存在内存泄露问题
        BaseContext.remove();
        return;
    }

    /**
     * 路径匹配，检查本次请求是需要拦截
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean check(String[] urls, String requestURL) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURL);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
